package April._22.answer.work2;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class Main {
    public static String password;
    //长度为1000的数组、用于存储猜测的密码
    public static String[] passwords = new String[(int) Math.pow(10, 3)];

    public static void main(String[] args) throws IOException, InterruptedException {

        // 随机生成密码
        password = createRandomPassword(3);
        System.out.println("password: " + password);
        // 启动穷举线程
        Thread matchThread = new Thread(
                // lambda表达式 也可以用匿名内部类
                () -> matchPassword(password)
        );
        matchThread.start();
        matchThread.join();
        // 启动日志线程
        System.out.println(Arrays.toString(passwords));
        Thread logThread = new Thread(
                () -> {
                    try (FileOutputStream out = new FileOutputStream("password.txt")) {

                        for (int i = 0; i < passwords.length; i++) {
                            if (passwords[i] != null) {
                                out.write(passwords[i].getBytes());
                                out.write("\r\n".getBytes());
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        );
        logThread.setDaemon(true);
        logThread.start();
        // 在这睡眠是为了让main线程不死,不死的话那么jvm中就还有用户线程,虚拟机就不会退出
        // 等到日志线程执行完了再死
        Thread.sleep(5000);
    }

    private static void matchPassword(String password) {
        // 所有的可能性就是000 - 999
        // 列一个 不是就放入到数组中
        for (int i = 0; i < passwords.length; i++) {
            /*
                这里进行了一次格式化字符串,表示将不足三位数的int值
                前面补0
                比如对于i=10,possiblePassword就=010
             */
            String possiblePassword = String.format("%03d", i);
            System.out.println(possiblePassword);
            if (password.equals(possiblePassword)) {
                break;
            } else {
                passwords[i] = possiblePassword;
            }
        }

    }

    /**
     *
     * @param len 密码长度
     * @return password
     */
    private static String createRandomPassword(int len) {
        char[] chars = new char[len];
        String s = "123456789";
        for (int i = 0; i < chars.length; i++) {
            chars[i] = s.charAt((int) (Math.random() * s.length()));
        }
        return new String(chars);
    }
}
